import axios from 'axios'
import type { AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
import { ElMessage } from 'element-plus'

// 创建验证码专用axios实例
const captchaService: AxiosInstance = axios.create({
  baseURL: 'https://localhost:7083/api/Captcha/', // 假设验证码服务路径
  timeout: 10000,
})

// 请求拦截器
captchaService.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 可在此处添加token等
    return config
  },
  (error) => Promise.reject(error)
)

// 响应拦截器
captchaService.interceptors.response.use(
  (response: AxiosResponse) => {
    const res = response.data
    if (res && res.code && res.code !== 200) {
      ElMessage.error(res.msg || '验证码请求失败')
      return Promise.reject(res)
    }
    return res
  },
  (error) => {
    ElMessage.error(error.response?.data?.msg || error.message || '验证码服务网络错误')
    return Promise.reject(error)
  }
)

// 获取验证码图片
export function getCaptcha() {
  // 假设后端接口为 GET /get，返回 { img, uuid }
  return captchaService.get('/get').then(res => res)
}

// 校验验证码
export function verifyCaptcha(data: { uuid: string, code: string }) {
  // 假设后端接口为 POST /verify，参数为 { uuid, code }
  return captchaService.post('/verify', data).then(res => res)
}

export default captchaService 